package com.hsd.whb.socket;

import com.alibaba.fastjson.JSONObject;
import com.hsd.whb.entity.Meeting;
import com.hsd.whb.entity.MeetingParticipateText;
import com.hsd.whb.enums.DeviceStatusEnum;
import com.hsd.whb.enums.MeetingStatusEnum;
import com.voice.client.Profile;
import com.voice.client.message.MessageClient;
import com.voice.client.message.MessageClientFactory;
import com.voice.client.message.callback.MessageCallback;
import com.wangjiacai.hqlQuery.repository.BaseRepository;
import com.wangjiacai.utils.utils.EnumUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

@Component
public class MeetingContext implements InitializingBean {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private BaseRepository baseRepository;

    @Override
    public void afterPropertiesSet() throws Exception {
        Profile profile = Profile.getAppKeyProfile("http://voice.emlab.net:8081", "24842048", "5b64076769d9c92e0169d9ccbd0jkh7f");

        MessageClient messageClient = MessageClientFactory.messageClient(profile);
        messageClient.connect(message -> {
            try {
                System.out.println(message);
                String topic = message.getTopic();
                String payload = new String(message.getPayload());
                JSONObject jsonObject = JSONObject.parseObject(payload);
                String deviceKey = jsonObject.getString("deviceKey");

                if (topic.equals("device_text_post")) {
                    String text = jsonObject.getString("text");
                    if (StringUtils.isEmpty(text)) return MessageCallback.Action.CommitSuccess;
                    Meeting meeting = getMeeting(deviceKey);
                    if (meeting == null) return MessageCallback.Action.CommitSuccess;
                    saveMeetingParticipateText(meeting.getId(), meeting.getSpeakerId(), text);
                }
                if (topic.equals("status_change_post")) {
                    int status = jsonObject.getInteger("status");
                    updateDeviceStatus(deviceKey, status);
                }

                if (topic.equals("device_message_penetrate")) {
                    byte[] data = jsonObject.getBytes("data");
                    JSONObject dataJson=JSONObject.parseObject(new String(data));
                    double dir=dataJson.getDouble("dir");
                    //todo 通过dir和divicekey获取说话人
                    String username="";
                    Meeting meeting=getMeeting(deviceKey);
                    messagingTemplate.convertAndSend("/topic/discern/" + meeting.getId(), username);
                }
                return MessageCallback.Action.CommitSuccess;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return MessageCallback.Action.CommitSuccess;
        });
    }

    private void saveMeetingParticipateText(int meetingId, Integer speakerId, String text) {
        if (speakerId == null) return;
        MeetingParticipateText meetingParticipateText = new MeetingParticipateText();
        meetingParticipateText.setDeleted(0);
        meetingParticipateText.setMeetingId(meetingId);
        meetingParticipateText.setParticipantsId(speakerId);
        meetingParticipateText.setText(text);
        meetingParticipateText.setStartTime(new Date());
        meetingParticipateText.setEndTime(meetingParticipateText.getStartTime());
        baseRepository.save(meetingParticipateText);
        messagingTemplate.convertAndSend("/topic/meeting/" + meetingId, text);
    }

    private Meeting getMeeting(String deviceKey) {
        String hql = "from Meeting where deviceId=(select id from Device where accessKey=:accessKey) and meetingStatus =:meetingStatus order by startTime desc";
        Map<String, Object> map = new HashMap<>();
        map.put("accessKey", deviceKey);
        map.put("meetingStatus", MeetingStatusEnum.PROGRESSING.getCode());
        return baseRepository.get(hql, map, Meeting.class);
    }

    private void updateDeviceStatus(String deviceKey, int deviceStatus) {
        DeviceStatusEnum deviceStatusEnum = EnumUtil.getEnumByCode(deviceStatus, DeviceStatusEnum.class);
        String hql = "update Device set deviceStatus=:deviceStatus where accessKey=:accessKey";
        Map<String, Object> map = new HashMap<>();
        map.put("accessKey", deviceKey);
        map.put("deviceStatus", deviceStatus);
        baseRepository.execute(hql, map);
        messagingTemplate.convertAndSend("/topic/device/" + deviceKey, deviceStatusEnum.getMessage());
    }
}
